package com.jike.shop.cloud.controller;

import com.google.gson.Gson;
import com.jike.shop.cloud.constant.ApiConstants;
import com.jike.shop.cloud.service.OrderService;
import com.jike.shop.common.dto.CreateOrderDTO;
import com.jike.shop.common.message.Replys;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(ApiConstants.API_VERSION + "/nacos")
@Slf4j
public class TestNacosController {


    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/instance/{ns}/{count}")
    public List<String> instance(@PathVariable("ns") String ns, @PathVariable("count") int count) {
        List<String> list = new ArrayList<>(count);
        for (int i=0;i<count;i++){
            String url = "http://127.0.0.1:8848/nacos/v1/ns/instance?port=8756&healthy=true&ip=127.0.0.1&weight=1.0&" +
                    "serviceName=" + System.currentTimeMillis() + i + "&encoding=GBK&namespaceId=" + ns;

            String result = restTemplate.postForObject(url, null, String.class);
            list.add(result);
        }
        return list;
    }

    @GetMapping("/beat")
    public String beat(){
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
        String queryUrl = "127.0.0.1:8848/nacos/v1/ns/service/list?pageNo=1&pageSize=1000&namespaceId=stress-test";
        String result = restTemplate.getForObject(queryUrl, null, String.class);
        ServiceDTO serviceDTO = new Gson().fromJson(result, ServiceDTO.class);
        for(String serviceName : serviceDTO.getServiceNames()){
            executorService.schedule(() -> {
                String beatUrl = "127.0.0.1:8848/nacos/v1/ns/instance/beat?serviceName=" + serviceName +"&beat=%7b%22cluster%22%3a%22c1%22%2c%22ip%22%3a%22127.0.0.1%22%2c%22metadata%22%3a%7b%7d%2c%22port%22%3a8080%2c%22scheduled%22%3atrue%2c%22serviceName%22%3a%22jinhan0Fx4s.173TL.net%22%2c%22weight%22%3a1%7d";
                restTemplate.put(queryUrl, null, String.class);
            }, 500, TimeUnit.MILLISECONDS);
        }
        return "OK";
    }


    @Data
    class ServiceDTO{
        private int count;
        private List<String> serviceNames;
    }
}

